const Service = require('./index')
const staffModel = require('@/models/staff.model')
const permissionModel = require('@/models/permission.model')
const jwt = require('jsonwebtoken')
const trash = require('@/utils/ini.util')

class StaffService extends Service {
  /**
   * 用户分页查询
   * @param {*} pageNo
   * @param {*} pageSize
   * @param {*} articleTitle
   * @param {*} status
   * @param {*} nickname
   * @param {*} username
   * @param {*} tel
   * @param {*} email
   */
  async findPage (pageNo = 1, pageSize = 20, {
    searchKeywords,
    email,
    tel,
    status,
    username,
    nickname
  }) {
    try {
      const { list, total } = await staffModel.findPage({
        pageNo,
        pageSize,
        andConditions: {
          equal: {
            'staff.status': status
          },
          like: {
            'staff.username': username,
            'staff.nickname': nickname,
            'staff.email': email,
            'staff.tel': tel
          }
        },
        orConditions: {
          like: {
            'staff.nickname': searchKeywords,
            'staff.username': searchKeywords
          }
        }
      })
      return this.skipPage(list.map(item => {
        return {
          ...item,
          password: undefined,
          roleNames: (item.roleNames || '').split(',').filter(Boolean),
          roleIds: (item.roleIds || '').split(',').filter(Boolean).map(Number)
        }
      }), total, pageNo, pageSize)
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 员工创建
   * @param {*} attrs
   * @returns
   */
  async create (attrs) {
    const { username, password, nickname, gender, status, avatar, email, tel, age } = attrs
    if (!username || !password) {
      return {
        errorMessage: '用户名或密码不能为空'
      }
    }
    try {
      const existUsername = await staffModel.existUsername(username)
      if (existUsername) {
        return {
          errorMessage: '用户名已经存在'
        }
      }
      const staffId = await staffModel.create({ username, password, nickname, gender, status, avatar, email, tel, age })
      return staffId
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 用户名密码登录
   * @param {*} username
   * @param {*} password
   * @returns
   */
  async login (username, password) {
    if (!username || !password) {
      return { errorMessage: '用户名和密码不能为空' }
    }
    try {
      const userInfo = await staffModel.findOneByUsername(username)
      if (!userInfo) {
        return { errorMessage: '该用户名不存在' }
      }
      if (userInfo.password !== password) {
        return { errorMessage: '密码错误' }
      }
      if (userInfo.status !== '1') {
        return { errorMessage: '该账号已被禁用' }
      }
      const permissionCodes = (await permissionModel.findPermissionByStaffId(userInfo.id)).map(o => o.code)
      if (!permissionCodes?.length) {
        return { errorMessage: '该用户无可用权限，请分配权限后再登录' }
      }
      const accessToken = jwt.sign({ id: userInfo.id }, trash.jsonSecretkey, { expiresIn: trash.expiresIn })
      return {
        ...userInfo,
        password: undefined,
        permissionCodes,
        accessToken
      }
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 员工信息更新
   * @param {*} id
   * @param {*} attrs
   * @returns
   */
  async update (id, attrs = {}) {
    if (this.isNull(id)) {
      return {
        errorMessage: '缺少必要标识id'
      }
    }
    try {
      const exist = await staffModel.exist(id)
      if (!exist) {
        return {
          errorMessage: '员工不存在'
        }
      }
      await staffModel.update(id, attrs)
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 更新员工状态
   * @param {*} id
   * @param {*} status
   * @returns
   */
  async updateStatus (id, status) {
    if (!['0', '1'].includes(status)) {
      return {
        errorMessage: '非法的status值'
      }
    }
    try {
      const exist = await staffModel.exist(id)
      if (!exist) {
        return {
          errorMessage: '员工不存在'
        }
      }
      await staffModel.updateStatus(id, status)
    } catch (error) {
      throw new Error(error)
    }
  }

  async delete (id) {
    if (this.isNull(id)) {
      return {
        errorMessage: 'id不能为空'
      }
    }
    try {
      await staffModel.delete(id)
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 批量删除员工
   * @param {*} ids
   */
  async batchDelete (ids) {
    if (!ids?.length) {
      return {
        errorMessage: 'ids不能为空'
      }
    }
    try {
      await staffModel.batchDelete(ids)
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 员工密码修改
   * @param {*} username
   * @param {*} password
  */
  async changePassword (attrs) {
    const { username, password, selfChange, oldPassword } = attrs
    if (!username || !password) {
      return {
        errorMessage: '用户名和新密码不能为空'
      }
    }
    try {
      const existUser = await staffModel.findOneByUsername(username)
      if (!existUser) {
        return {
          errorMessage: '用户不存在'
        }
      }
      if (selfChange) {
        if (existUser.password !== oldPassword) {
          return {
            errorMessage: '用户旧密码不正确'
          }
        }
      }
      await staffModel.updatePassword(username, password)
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new StaffService()
